package com.wyh.contorller;

import com.wyh.entity.Account;
import com.wyh.entity.RestBean;
import com.wyh.mapper.UserMapper;
import com.wyh.service.AuthorizeService;
import org.hibernate.validator.constraints.Length;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.Pattern;

@Validated
@RestController
@RequestMapping("/api/auth")
public class AuthorizeController {
// MV C
    @Resource
    UserMapper usermapper;

    @Resource
    BCryptPasswordEncoder encoder;

//    @Resource
//    captchaMapper captchamapper;

    private final String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
    private final String USERNAME_REGEX = "^[a-zA-Z0-9_.-]+$";

    @Resource
    AuthorizeService service;

    @PostMapping("/valid-email")
    public RestBean<String> validEmail(@Pattern(regexp = EMAIL_REGEX) @RequestParam("email") String email) {
        String s = service.sendValidateEmail(email);
        if (s == null)
            return RestBean.success("邮件已发送，请注意查收");
        else
            return RestBean.failure(400, s);

    }

    @PostMapping("/register")
    public RestBean<String> register(
            @Length(min = 6, max = 16) @RequestParam("password") String password,
            @Pattern(regexp = EMAIL_REGEX) @RequestParam("email") String email,
            @Length(min = 6, max = 6) @RequestParam("code") String code) {
        // ------------------------------------------------------------
        @Pattern(regexp = USERNAME_REGEX) @Length(min = 2, max = 8) String username = "user_" + email.substring(4);//随机生成username

        String s = service.validateAndRequest(username, password, email, code);
        //判断数据是福哦正确，并且录入数据库
        if (s == null) {
            Account user = new Account();
            user.setUsername(username);
            user.setPassword(encoder.encode(password));
            user.setEmail(email);
            usermapper.insertAccount(user);
            return RestBean.success("注册成功");
        } else
            return RestBean.failure(400, "注册失败,验证错误");
    }


//    @PostMapping("/test")
//    public RestBean<String> test(Account account) {
//
//        account.setPassword(encoder.encode(account.getPassword()));
//        usermapper.insertAccount(account);
//        return RestBean.success("yes");
//    }

}
